/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
package com.wealth.coupon.web.controller;

import java.util.Date;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.coupon.entity.Coupon;
import com.wealth.coupon.enums.CouponStatusEnum;
import com.wealth.coupon.service.ICouponService;
import com.wealth.system.entity.User;
import com.wealth.system.service.ShiroUser;
import com.wealth.system.web.controller.BaseController;

import iaas.enums.StatusEnum;
import iaas.upload.ApiDownService;
import iaas.utils.RedirectMessage;
import iaas.utils.ResultObject;
import iaas.web.JqGridRequest;
import iaas.web.JqGridResponse;
import iaas.web.JqGridUtil;

/**
 * @author chan
 * @version 1.0
 * @since 1.0
 */

@Controller
@RequestMapping(value = "/manage/coupon/coupon")
public class CouponController extends BaseController {

	Logger logger = Logger.getLogger(CouponController.class);

	@Autowired
	private ICouponService couponService;

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Classify对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void init(@RequestParam(value = "id", defaultValue = "-1") Long id,
			Model model) {
		try {
			if (id != -1) {
				Coupon coupon = couponService.get(id);
				model.addAttribute("coupon", coupon);
			}
		} catch (Exception e) {
			logger.error("初始化错误", e);
		}
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) {
		Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
		model.addAttribute("corpid", corpid);
		return "coupon/coupon/list";
	}

	/**
	 * 列表ajax查询数据
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public JqGridResponse getJson(Model model, JqGridRequest request) {
		try {

			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();

			Page<Coupon> page = couponService.get(corpid, request, Coupon.class);

			return JqGridUtil.getJqGrirdResponse(page);
		} catch (Exception e) {
			logger.error("列表错误！", e);
			return null;
		}
	}

	/**
	 * 详情
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String infoForm(Model model, @PathVariable("id") Long id) {
		try {
			Coupon coupon = couponService.get(id);
			model.addAttribute("coupon", coupon);
			return "coupon/coupon/info";
		} catch (Exception e) {
			logger.error("详情页面错误,id=" + id, e);
			return "system/500";
		}
	}

	/**
	 * 创建页面
	 */
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String createForm(Model model) {
		try {
			//企业ID
			//Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();	
			return "coupon/coupon/create";
		} catch (Exception e) {
			logger.error("创建页面错误", e);
			return "system/500";
		}
	}

	/**
	 * 保存
	 */
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(Model model,@Valid Coupon coupon,RedirectAttributes redirectAttributes) {
		try {
			//保存批次表
			User user = ShiroUser.getInstance().getUser();
			coupon.setCorp(user.getCorp());
			coupon.setStatus(StatusEnum.NORMAL.getValue());
			coupon.setStartno(100001);
			coupon.setEndno(100000 + coupon.getQuantity());
			coupon.setCreator(user.getUsername());
			coupon.setCreateTime(new Date());
			ResultObject rs = couponService.saveCoupon(coupon);
			if(!rs.getCode().equals("000")){
				redirectAttributes.addFlashAttribute("message",RedirectMessage.setShowTipWarning("非纸质模式的优惠券批次，只能创建一个"));
				return "redirect:/manage/coupon/coupon/list";
			}
			
			redirectAttributes.addFlashAttribute("message",RedirectMessage.setShowTipSuccess("创建成功"));
			return "redirect:/manage/coupon/coupon/list";
		} catch (Exception e) {
			logger.error("创建错误", e);
			return "system/500";
		}
	}

	/**
	 * 编辑页面
	 */
	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String setUpdateForm(Model model, @PathVariable("id") Long id) {
		try {
			Coupon coupon = couponService.get(id);
			model.addAttribute("coupon", coupon);
			return "coupon/coupon/update";
		} catch (Exception e) {
			logger.error("编辑页面错误,id=" + id, e);
			return "system/500";
		}
	}

	/**
	 * 编辑
	 */
	@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
	public String update(@PathVariable("id") Long id,@ModelAttribute("coupon") Coupon coupon,RedirectAttributes redirectAttributes) {
		try {
			couponService.save(coupon);
			redirectAttributes.addFlashAttribute("message",RedirectMessage.setShowTipSuccess("编辑成功，请重新下载"));
			return "redirect:/manage/coupon/coupon/list";
		} catch (Exception e) {
			logger.error("编辑错误,id=" + id, e);
			return "system/500";
		}
	}

	/**
	 * 删除（逻辑删除）
	 */
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public String delete(@PathVariable Long id,
			RedirectAttributes redirectAttributes) {
		try {
			couponService.deleteLogical(id);
			redirectAttributes.addFlashAttribute("message",
					RedirectMessage.setShowTipSuccess("删除成功"));
			return "redirect:/manage/coupon/coupon/list";
		} catch (Exception e) {
			logger.error("删除错误,id=" + id, e);
			return "system/500";
		}
	}

	/**
	 * 制作优惠券文件
	 */
	@RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
	public void download(Model model, @PathVariable Long id,
			RedirectAttributes redirectAttributes,HttpServletResponse response) {
		try {
			boolean con = false;
			con = couponService.createCouponFile(id);
			Coupon coupon = couponService.get(id);
			if (con) {
				redirectAttributes.addFlashAttribute("message",RedirectMessage.setShowTipSuccess("标签生成成功"));
			} else {
				coupon.setStatus(CouponStatusEnum.NOTPASS.getValue());
				couponService.save(coupon );
				redirectAttributes.addFlashAttribute("message",RedirectMessage.setShowTipWarning("标签生成失败"));
			}
			
			
			ApiDownService apiDownService = new ApiDownService();
			StringBuffer filename = new StringBuffer("");
			filename.append("优惠券_");
			filename.append(coupon.getId());
			filename.append(".txt");
			apiDownService.downLableFile(coupon.getFilepath(),filename.toString(), response);
					
		} catch (Exception e) {
			logger.error("制作优惠券文件错误", e);
		}
	}

	/**
	 * 停用
	 */
	@RequestMapping(value = "/disable/{id}", method = RequestMethod.GET)
	public String disable(@PathVariable Long id,
			RedirectAttributes redirectAttributes) {
		try {
			couponService.updateStatus(id, StatusEnum.STOP.getValue());
			redirectAttributes.addFlashAttribute("message",
					RedirectMessage.setShowTipWarning("停用成功"));
			return "redirect:/manage/coupon/coupon/list";
		} catch (Exception e) {
			logger.error("停用错误,id=" + id, e);
			return "system/500";
		}
	}

	/**
	 * 启用
	 */
	@RequestMapping(value = "/enable/{id}", method = RequestMethod.GET)
	public String enable(@PathVariable Long id,
			RedirectAttributes redirectAttributes) {
		try {
			couponService.updateStatus(id, StatusEnum.NORMAL.getValue());
			redirectAttributes.addFlashAttribute("message",
					RedirectMessage.setShowTipWarning("启用成功"));
			return "redirect:/manage/coupon/coupon/list";
		} catch (Exception e) {
			logger.error("启用错误,id=" + id, e);
			return "system/500";
		}
	}
}